package org.mte.swift.builder.template;

import java.util.Iterator;

import org.mte.swift.builder.model.SwiftModel;
import org.mte.swift.builder.model.app.AppModel;
import org.mte.swift.builder.model.placeholder.Placeholder;
import org.mte.swift.builder.model.template.Template;

public class TemplateProcessorImpl implements TemplateProcessor {

	
	public void processTemplates(SwiftModel swiftModel) throws Exception {
		for (AppModel appModel : swiftModel.getAppModels()) {
			for (Template template : swiftModel.getTemplateSet().getEntities()) {
				Iterator<Placeholder> iterator = appModel.getPlaceholderMap().keySet().iterator();
				String templatePath = replaceKey(template.getPath(),
						Placeholder.ENTITY_CAPITALIZE_PH,
						appModel.getEntity().getName());
				templatePath = replaceKey(templatePath,
						Placeholder.ENTITY_LOWER_CASE_PH,
						appModel.getEntity().getLowName());
				if (template.isWeb()) {
					templatePath = appModel.getWebPath() + templatePath;
				} else if (template.isJava()) {
					templatePath = swiftModel.getSourcePath() + templatePath;
					
				}
				String templateContent = template.getContent();
				while (iterator.hasNext()) {
					Placeholder placeholder = iterator.next();
					String value = appModel.getPlaceholderValue(placeholder);
					templateContent = replace(templateContent, placeholder, value);					
				}
				appModel.getTemplateSet().add(new Template(templatePath, templateContent, template.getType()));
			}
		}
	}
	
    private String replace(String txt, Placeholder placeholder, String value) {
    	if (txt != null && txt.indexOf(placeholder.name) != -1 && value != null) {
    		txt = txt.replaceAll(placeholder.regex, value);
    	}
    	return txt;
    }
    
    public String replaceKey(String txt, Placeholder placeholder, String value) {
    	if (txt != null && txt.indexOf(placeholder.key) != -1 && value != null) {
    		txt = txt.replaceAll(placeholder.key, value);
    	}
    	return txt;
    }

 
}
